import { relationalStore } from '@kit.ArkData'
import { circle } from './circle'

const STORE_CONFIG = {
  name: 'RdbTest.db', // 数据库文件名
  securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别
}

// 建表sql语句
const SQL_CREATE_TABLE_3 = 'CREATE TABLE IF NOT EXISTS CIRCLE (ID INTEGER PRIMARY KEY, CNAME TEXT NOT NULL, COMMENT TEXT NOT NULL)'

class CircleDatabase{
  private contactDataRdbStore: relationalStore.RdbStore

  createNow(context){
    relationalStore.getRdbStore(context, STORE_CONFIG, (err, store)=>{
      if (err) {
        console.error('失败', err);
        return;
      }
      console.info('成功')
      store.executeSql(SQL_CREATE_TABLE_3)
      this.contactDataRdbStore = store;
    })
  }
  // 添加圈子评论
  saveNewCircle(cname: string, comment: string){
    let valueCircle = {
      'CNAME': cname,
      'COMMENT': comment
    }
    this.contactDataRdbStore.insert('CIRCLE', valueCircle, (err, rowId)=>{
      if (err) {
        console.error('存放数据失败', err)
        return;
      }
      console.info('存放数据成功，行ID：', rowId)
    })
  }
  // 查询所有参数
  CircleContacts(callback: Function){
    // 创建谓词
    let predicates = new relationalStore.RdbPredicates('CIRCLE')
    // 调用query()方法查找数据，返回一个ResultSet结果集
    this.contactDataRdbStore.query(predicates,['ID','CNAME','COMMENT'],(err,resultSet)=>{
      if (err) {
        console.error(`Failed to query data. Code:${err.code},message:${err.message}`)
        return
      }
      console.info(`ResultSet column names:${resultSet.columnNames}`)
      console.info(`ResultSet column count:${resultSet.columnNames}`)
      console.info(`ResultSet:${JSON.stringify(resultSet)}`)
      // resultSet是一个数据集合的游标，默认指向第-1个记录，有效的数据从0开始。
      let count: number = resultSet.rowCount
      resultSet.goToFirstRow()
      let result: circle[] = []
      for(let i = 0; i < count; i++){
        let tmp: circle = {id: '', cname: '', comment: ''}
        tmp.id = resultSet.getString(resultSet.getColumnIndex('ID'))
        tmp.cname = resultSet.getString(resultSet.getColumnIndex('CNAME'))
        tmp.comment = resultSet.getString(resultSet.getColumnIndex('COMMENT'))
        result[i] = tmp
        resultSet.goToNextRow()
      }
      // 释放数据集的内存
      resultSet.close()
      for(let i = 0; i < result.length; i++){
        console.info(`Final result: ${JSON.stringify(result[i])}`)
      }
      // 创建倒序数组
      let result1: circle[] = result.slice().reverse()
      callback(result1)
    })
  }
}
let circleDatabase = new CircleDatabase()
export default circleDatabase